package com.imooc.dom4j;

import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class HrReader {
	public void readXml() {
		//读取文件
		String file = "D:\\pro_software\\eclipse-workspace\\xml\\src\\com\\imooc\\dom4j\\hrTest.xml";
		//SAXReader类是读取XML文件的核心类，用于将XML解析后以树的形式保存到内存中
		SAXReader reader = new SAXReader();		
		try {
			Document document = reader.read(file);
			//获取XML文档的根节点，即hr标签
			Element root = document.getRootElement();
			//elements方法用于获取employee标签集合
			List<Element> employees = root.elements("employee");
			//for循环遍历employee标签集合
			for (Element employee : employees) {
				//element方法用于获取唯一的子节点对象
				//getText方法用于获取标签文本
				System.out.println(employee.elementText("age"));
				System.out.println(employee.element("age").getText());
				//employee.elementText("age")和employee.element("age").getText()效果一样
				
				System.out.println(employee.elementText("salary"));
				Element department = employee.element("department");
				System.out.println(department.elementText("dname"));
				System.out.println(department.elementText("address"));
				//attribute获得节点属性
				Attribute att = employee.attribute("no");
				System.out.println(att.getText());

			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}				
				
	}
	
	public static void main(String[] args) {
		HrReader hr = new HrReader();
		hr.readXml();
	}
	
}
